package com.hjq.demo.ui.act

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.View.OnLongClickListener
import android.view.WindowManager
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.google.android.material.button.MaterialButton
import com.google.android.material.textview.MaterialTextView
import com.google.gson.Gson
import com.hjq.base.BaseDialog
import com.hjq.demo.R
import com.hjq.demo.app.AppActivity
import com.hjq.demo.http.HttpCacheManager
import com.hjq.demo.http.WebSocketManager
import com.hjq.demo.http.api.AppInfoApi
import com.hjq.demo.http.api.MyIntercept
import com.hjq.demo.http.glide.GlideApp
import com.hjq.demo.http.model.AppM
import com.hjq.demo.http.model.BannerHolderCreator
import com.hjq.demo.http.model.SocketModel
import com.hjq.demo.http.model.VersionApi
import com.hjq.demo.http.model.VersionM
import com.hjq.demo.manager.ActivityManager
import com.hjq.demo.manager.MmkvUtil
import com.hjq.demo.other.AppConfig
import com.hjq.demo.other.AppConfig.getVersionCode
import com.hjq.demo.other.EventShowTime
import com.hjq.demo.other.ReRun
import com.hjq.demo.other.RenewTipEvent
import com.hjq.demo.other.SocketError
import com.hjq.demo.other.SocketEvent
import com.hjq.demo.ui.activity.AdminActivity
import com.hjq.demo.ui.activity.CrashActivity
import com.hjq.demo.ui.activity.SplashActivity
import com.hjq.demo.ui.adapter.MealAdapter
import com.hjq.demo.ui.dialog.OrderGuideDialog
import com.hjq.demo.ui.dialog.UpdateDialog
import com.hjq.demo.widget.PriceDivi
import com.hjq.demo.worktask.TaskGoHome
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallback
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.hjq.widget.layout.WrapRecyclerView
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.enums.SidePattern
import com.stx.xhb.xbanner.XBanner
import com.stx.xhb.xbanner.entity.CustomViewsInfo
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.coroutines.launch
import okhttp3.Call
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.util.Locale


/**
 *  输液椅  首页
 *  atttention : 本界面频繁处于后台  有提示只能用吐司 不能用Dialogx等弹框
 */


class MainAct : AppActivity() {
    private val iv: AppCompatImageView? by lazy { findViewById(R.id.iv) }
    private val iv_bg: AppCompatImageView? by lazy { findViewById(R.id.iv_bg) }
    private val btn_submit: MaterialButton? by lazy { findViewById(R.id.btn_submit) }
    private val btn_renew: MaterialButton? by lazy { findViewById(R.id.btn_renew) }
    private val et_min: AppCompatEditText? by lazy { findViewById(R.id.et_min) }
    private val list_meal: WrapRecyclerView? by lazy { findViewById(R.id.list_meal) }
    private val tv_time: MaterialTextView? by lazy { findViewById(R.id.tv_time) }
    private val tv_busi: MaterialTextView? by lazy { findViewById(R.id.tv_busi) }
    private val tv_service: MaterialTextView? by lazy { findViewById(R.id.tv_service) }
    private val tv_hospital: MaterialTextView? by lazy { findViewById(R.id.tv_hospital) }
    private val tv_hospital1: MaterialTextView? by lazy { findViewById(R.id.tv_hospital1) }
    private val tv_sn: MaterialTextView? by lazy { findViewById(R.id.tv_sn) }
    private val lin_admin: LinearLayoutCompat? by lazy { findViewById(R.id.lin_admin) }


    private val tv1: TextView? by lazy { findViewById(R.id.tv1) }
    private val xbanner: XBanner? by lazy { findViewById(R.id.xbanner) }
    private lateinit var audioManager: AudioManager


    /*lateinit var tv_remain: MaterialTextView
    lateinit var tv_offline: MaterialTextView*/
    var tv_online: MaterialTextView? = null
    var tv_offline: MaterialTextView? = null
    var tv_remain: MaterialTextView? = null

    /**
     * 订单是否进行中
     */
    private var userUsing = false
    private var hosName = ""


    private var mealAdapter = MealAdapter(this);
    override fun getLayoutId(): Int {
        return R.layout.layout_main;
    }


    //隐藏SystemUI
    fun hideNavigation(context: Context?): Boolean {

//        val dpm = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager;
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        decorView.systemUiVisibility = uiOptions
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN
        );

        var ishide: Boolean
        try {
            val command: String
            command =
                "LD_LIBRARY_PATH=/vendor/lib:/system/lib service call activity 42 s16 com.android.systemui"
            val proc = Runtime.getRuntime().exec(
                arrayOf(
                    "su", "-c", command
                )
            )
            proc.waitFor()
            ishide = true
        } catch (ex: java.lang.Exception) {
            Toast.makeText(
                context, ex.message, Toast.LENGTH_LONG
            ).show()
            ishide = false
        }
        return ishide
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        Timber.d("案件  $keyCode ${event?.action}")
        return super.onKeyDown(keyCode, event)
    }


    override fun onDestroy() {
        super.onDestroy()
        isDestory = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun recRenew(json: RenewTipEvent) {
//         播放续费语音提示
        if (json.socketJson == null || json.socketJson == "") {
//            续费
            screenTip(false, json.socketJson)
            if (userUsing) {
                if (!mediaPlayerRe.isPlaying) {
                    mediaPlayerRe.start();
                }
            }
        } else {

            //            订单结束
            voiceContent = json.socketJson
            screenTip(false, voiceContent)


        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun recTimeShow(json: EventShowTime) {
        tv_time?.setText("${json.endTime}秒后结束  ${json.tipTime}秒提醒 ")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun recSocketErr(json: SocketError) {
        Timber.d("recSocketErr  ")
        tv_online?.visibility = View.GONE
        tv_offline?.text = "离线"
        tv_offline?.visibility = View.VISIBLE
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun recSocket(json: SocketEvent) {
        Timber.d("recSocket  ")
        task2CheckFront();
        val str = json.socketJson
        val gsonData = Gson().fromJson(str, SocketModel::class.java);
        /**
         *  分钟数
         */
        val socketData = gsonData.data;

        when (gsonData.type) {
            "start" -> {
//                 指令
                orderStart(socketData)
            }

            "renew" -> {
//                 指令
                orderRenew(socketData)
            }

            "end" -> {
//                停止指令
                orderEnd()
            }

            "heart" -> {
//                Timber.i("心跳收到  ")
                if (tv_online?.visibility == View.GONE || tv_offline?.visibility == View.VISIBLE) {
                    tv_online?.visibility = View.VISIBLE
                    tv_offline?.visibility = View.GONE
                }
                lifecycleScope.launch {
                    reqAppInfo()
                    reqVersion()
                }

//              设备端 30s 主动发一次，如果连续 2 次收不到回复，设备要重新发起登录  需要重新登陆
            }

            else -> {

            }

        }
    }

    private var endTimestamp = 0L;

    /**
     *  任务1 ：在 n 分钟后 结束订单
     *  任务2 ：在 n-x 分钟后 对用户提示  x分钟后订单结束
     */
    private fun orderStart(miniutesLong: String) {
        userUsing = true;
//         为了防止应用被杀，将结束时间 存文件
        val seconds = System.currentTimeMillis() / 1000 //实时时间戳
//        val orderSeconds = miniutesLong.toLong() * 60;// 订单时长：秒
        endTimestamp = seconds + 60 * miniutesLong.toLong()
        MmkvUtil.saveLong(MmkvUtil.EndTime, endTimestamp);
        orderStart1()
    }

    /**
     *  剩余秒数
     */
    private var orderSeconds = 0L;
    private fun orderStart1() {
        val seconds = System.currentTimeMillis() / 1000 //实时时间戳
        orderSeconds = endTimestamp - seconds;
        //        创建订单时 用到，
        reRunRec = ReRun();
        val filter = IntentFilter(TaskGoHome.tag);
//        play(true, "欢迎使用，$miniutesLong 分钟后到期")
        registerReceiver(reRunRec, filter)
        TaskGoHome.goMain(orderSeconds)  // https://gl.ali213.net/html/2023-9/1139803.html

//        TaskGoHome.goMain(miniutesLong.toLong())//todo  测试用 不要打开
        ToastUtils.show("$orderSeconds 秒后到期~")
        remainTimeCountDown(orderSeconds)
        postDelayed({
            startActivity(AppListAct::class.java)/*ActivityManager.getInstance().finishActivity(MainAct::class.java)
            ActivityManager.getInstance().finishActivity(SplashActivity::class.java)*/
        }, 500)
    }

    /**
     *  在原结束时间基础上  追加 miniutesLong 分钟
     */
    private fun orderRenew(miniutesLong: String) {
        userUsing = true;
        val oldEndTime = MmkvUtil.getLong(MmkvUtil.EndTime, 0);
        val newEnd = oldEndTime + miniutesLong.toLong() * 60

        Timber.d("原结束：$oldEndTime 续费：$miniutesLong 分钟  最终结果：↓ ")

//   延时时间应该是： 新的结束时间  减去  当前时间 的时间间隔
        val seconds = System.currentTimeMillis() / 1000 //实时时间戳
        MmkvUtil.saveLong(MmkvUtil.EndTime, newEnd);// 续费时及时更新本地时间戳
        val newDelay = newEnd - seconds
        Timber.d("续费到 $newEnd")
        remainTimeCountDown(newDelay.toLong())
        screenTip(false, "续费成功")
        TaskGoHome.goMain(newDelay)
    }

    /**
     *  无条件执行订单结束  回到应用的操作
     */
    private fun orderEnd() {
        endTimestamp = 0L;
        MmkvUtil.saveLong(MmkvUtil.EndTime, endTimestamp);
        userUsing = false;
        setRemainSeconds(0)
        countDownTimer.onFinish()
        TaskGoHome.goMain(1);
    }

    lateinit var reRunRec: ReRun;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MmkvUtil.save(MmkvUtil.IsBackCheck, true)
        endTimestamp = MmkvUtil.getLong(MmkvUtil.EndTime, 0);
        Timber.d("订单结束时间 $endTimestamp");
        userUsing = endTimestamp > (System.currentTimeMillis() / 1000);// 订单是否进行中 结束时间大于当前 时间，才是没结束
        if (userUsing && AppConfig.isDebug()) {
//            orderStart1()//todo  仅供调试
        }
        Timber.d("onCreate(savedInstanceState: Bundle?)")
        if (!EventBus.getDefault()
                .hasSubscriberForEvent(RenewTipEvent::class.java) && !EventBus.getDefault()
                .hasSubscriberForEvent(EventShowTime::class.java) && !EventBus.getDefault()
                .hasSubscriberForEvent(SocketEvent::class.java)
        ) {
            Timber.d("未订阅")
            EventBus.getDefault().register(this)
        } else {
            Timber.d("已订阅")
        }
    }

    /**
     * 背景图
     */
    private var bgUrl = ""
    private var mealList = mutableListOf<AppM.DataDTO.SetMealDTO>();
    private var voiceContent = "";
    private fun reqAppInfo() {
        val eqSn = MmkvUtil.getString(MmkvUtil.DeviceCode, "");
        if (eqSn == "") {
            ToastUtils.show("先设置设备编号..")
            return;
        }
        EasyHttp.post(this).api(AppInfoApi().setEquipment(eqSn))
            .delay(HttpCacheManager.getRandomDelay()).request(object : HttpCallback<AppM>(this) {
                override fun onFail(e: Exception?) {
                    super.onFail(e)
                }

                override fun onSucceed(result: AppM?) {
                    super.onSucceed(result)
                    if (result?.code == 1) {
                        if (result != null) {
                            loadPageData(result.data)
                        }
                    } else {
                        ToastUtils.show("${result?.msg}")
                    }

                }

                override fun onEnd(call: Call?) {
                    super.onEnd(call)
//                    tv_hospital?.text = "$hosName  ${MmkvUtil.getString(MmkvUtil.DeviceCode, "")}"
                    tv_hospital1?.text = "${MmkvUtil.getString(MmkvUtil.DeviceCode, "")} $hosName"
//                    tv_sn?.text =
                }
            })
    }

    private fun loadPageData(res: AppM.DataDTO) {
        if (res != null) {
            tv_busi?.text = res.businessMobile;
            tv_service?.text = res.serviceMobile;
            hosName = res.hospitalName
            MmkvUtil.save(MmkvUtil.HosName, hosName);
            val url = res?.qrcodePath
            voiceContent = res?.voice!!;
            GlideApp.with(getContext()).load(url).into(iv!!)
            mealList = res?.setMeal!!
//        mealList.addAll(mealList)
            bgUrl = res?.backImg.toString();
            if (bgUrl == "" || !bgUrl.startsWith("http")) {
//                ToastUtils.show("背景图有误，已加载默认图")
            }
//            GlideApp.with(getContext()).load(bgUrl).into(iv_bg!!)
            mealAdapter.setData(mealList);
            val remind_minute = res?.remindMinute;

//                     将提前提醒的分钟数 存文件 创建任务时 在获取
            MmkvUtil.save(MmkvUtil.PreTipMiniutes, remind_minute);
            loadBanner(res.banner)
        }

    }

    /**
     * 加载轮播图
     */
    private fun loadBanner(b: MutableList<AppM.DataDTO.BannerDTO>) {
        var banners = mutableListOf<CustomViewsInfo>()
        for (item in b) {
            banners.add(CustomViewsInfo(item.image, item.type))
        }

        val holderCreator = BannerHolderCreator()
        xbanner?.setBannerData1(banners, holderCreator)

        xbanner?.setOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(i: Int, v: Float, i1: Int) {

            }

            override fun onPageSelected(i: Int) {
//                Log.i("onPageSelected=", i.toString() + "")
                val isVideo = banners.get(i).type == 2
                if (isVideo) {
                    holderCreator?.videoViewHolder?.videoView?.start()
                } else {
                    holderCreator?.videoViewHolder?.videoView?.pause()
                }
            }

            override fun onPageScrollStateChanged(i: Int) {
//                Log.i("ScrollStateChanged=", i.toString() + "")
            }
        })
    }

    private val screenTip = "请扫右上角二维码进行观看"
    override fun initView() {
        hideNavigation(this)/*val tp = tv_sn?.paint;
        tp?.strokeWidth = 1f;
        tp?.style = Paint.Style.FILL_AND_STROKE;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            tp?.color = getColor(R.color.pink);
        } else {
            tp?.color = ContextCompat.getColor(this, R.color.pink);
        }
        tv_sn?.setTextColor(ContextCompat.getColor(this, R.color.orange))*/
        mediaPlayer = MediaPlayer.create(this, R.raw.order_new)
        mediaPlayerRe = MediaPlayer.create(this, R.raw.order_re)

        list_meal?.addItemDecoration(PriceDivi())
        list_meal?.layoutManager = LinearLayoutManager(this);
        list_meal?.adapter = mealAdapter
        btn_renew?.setOnClickListener {
//            测试函数
            orderRenew("1")
        }
        btn_submit?.setOnClickListener {
            var s = et_min?.text?.trim().toString()
            if (s == "") {
                s = "2";
            }
            orderStart(s);
        }
        btn_submit?.setOnLongClickListener(object : OnLongClickListener {
            override fun onLongClick(v: View?): Boolean {
                CrashActivity.start(application, Throwable("adsfad"))
                return true;
            }

        })
        lin_admin?.setOnLongClickListener(object : OnLongClickListener {
            override fun onLongClick(v: View?): Boolean {
                toAdmin()
                return true;
            }
        });
        iv?.setOnLongClickListener(object : OnLongClickListener {
            override fun onLongClick(v: View?): Boolean {
                toAdmin()
                return true;
            }
        });

        orderGuideDialog = OrderGuideDialog.Builder(this)
        screenTips()
    }

    private fun toAdmin() {
        userUsing = true;
        Timber.d("返回3")
        startActivity(AdminActivity::class.java)
    }

    /**
     * 集中管理  点击屏幕的提示
     */
    private fun screenTips() {/*window.decorView.setOnTouchListener(object : OnTouchListener {
    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        ToastUtils.show("33333 $screenTip")
        play(true, "$screenTip")
        return true
    }

})*/
        findViewById<AppCompatImageView>(R.id.iv_bg)?.setOnClickListener {
            screenTip(true, "$screenTip")
        }
        findViewById<LinearLayoutCompat>(R.id.root_meal)?.setOnClickListener {
            screenTip(true, "$screenTip")
        }
        findViewById<AppCompatImageView>(R.id.iv)?.setOnClickListener {
            screenTip(true, "$screenTip")
        }
        xbanner?.setOnItemClickListener { banner, model, view, position ->
            screenTip(true, "$screenTip")
        }
        list_meal?.setOnClickListener {
//            play(true, "$screenTip")
        }/*list_meal?.setOnTouchListener(object : OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                screenTip(true, "$screenTip")
                return true;
            }

        })*/
        findViewById<ConstraintLayout>(R.id.root)?.setOnClickListener {
            screenTip(true, "$screenTip")
            ToastUtils.show("111111111 $screenTip")
        }
    }

    /*override fun onTouchEvent(event: MotionEvent?): Boolean {
        play(true, "$screenTip")
        ToastUtils.show("22222222222 $screenTip")
//        return super.onTouchEvent(event)
        return true
    }*/

    fun setBrightness(brightness: Int) {
        try {
            val resolver = contentResolver
            val uri = Settings.System.getUriFor("screen_brightness")
            Settings.System.putInt(resolver, "screen_brightness", brightness)
            resolver.notifyChange(uri, null)
//            Timber.i("Brightness", "Brightness set to $brightness")
        } catch (e: SettingNotFoundException) {
            Timber.e("Brightness", "Cannot access system brightness")
            e.printStackTrace()
        }
    }

    private fun devInfo() {
        val stringBuilder = StringBuilder()
        stringBuilder.append(AppConfig.getVersionName())
        stringBuilder.append("-")
        stringBuilder.append(AppConfig.getVersionCode())
        if (AppConfig.getBuildType() != "release") {
            stringBuilder.append(AppConfig.getBuildType())
        }
        stringBuilder.append("-sn:" + MmkvUtil.getString(MmkvUtil.DeviceCode, "-"))
        val msg = stringBuilder.toString().trim();
        tv1?.text = "$msg"
    }

    override fun initData() {
        permissionNotification()
        devInfo()
        if (!isFinishing) {
            audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
            reqAppInfo()
            WebSocketManager.getInstance().connectWebSocket()
            initTextToSpeech()
            postDelayed({
                delayDialog()
            }, 1000)
        }
    }

    /**
     *无人值守设备 初次安装  将所需权限一次性 申请完毕
     */
    private fun permissionNotification() {
        XXPermissions.with(this).permission(
            Permission.NOTIFICATION_SERVICE,
        )

            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    reqVersion()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    super.onDenied(permissions, doNotAskAgain)
                    permissionNotification()
                }

            })
    }

    private fun delayDialog() {
        if (!isFinishing) XXPermissions.with(this)
            .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.WRITE_SETTINGS)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {

                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
                        showAppFloat()
                    } else {
//   跳转系统设置
                        if (!Settings.canDrawOverlays(getContext())) {
                            val intent = Intent()
                            intent.action = Settings.ACTION_MANAGE_OVERLAY_PERMISSION
                            startActivity(intent)
                            return
                        } else {
                            showAppFloat()
                        }
                    }

                }

                override fun onDenied(
                    permissions: MutableList<String>, doNotAskAgain: Boolean
                ) {
                    super.onDenied(permissions, doNotAskAgain)
                    ToastUtils.show("悬浮窗权限拒绝了 ...")
                }
            })
    }

    private fun showAppFloat() {
        EasyFloat.with(this.applicationContext).setShowPattern(ShowPattern.ALL_TIME)
            .setSidePattern(SidePattern.RESULT_SIDE).setImmersionStatusBar(true)
            .setGravity(Gravity.START, 0, 90).setLayout(R.layout.window_system) {

                tv_remain = it.findViewById<MaterialTextView>(R.id.tv_remain)!!
                tv_offline = it.findViewById(R.id.tv_offline)
                tv_online = it.findViewById(R.id.tv_online)

                val maxVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
                val currentVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
                val seekVol = it.findViewById<SeekBar>(R.id.seek_vol)
                val seek_brightniss = it.findViewById<SeekBar>(R.id.seek_brightniss)
                val btn_backhome = it.findViewById<MaterialButton>(R.id.btn_backhome)
                val btn_backhome1 = it.findViewById<MaterialButton>(R.id.btn_backhome1)
                btn_backhome?.setOnClickListener {
//                    MessageDialog.build().setTitle("我是弹框").show()
                    Timber.d("返回2")
                    if (userUsing) {
                        startActivity(AppListAct::class.java)
                    } else {
                        startActivity(MainAct::class.java)
                    }
//                     测试订单操作  倒计时
//                    remainTimeCountDown(10)
                }
                btn_backhome1?.setOnClickListener {
                    finishActivity(0)
                    ActivityManager.getInstance().finishActivity(MainAct::class.java)
//                    finish()
                }
                seekVol.max = maxVol
                seekVol.progress = currentVol
                Timber.d("最大媒体音量 $maxVol")
                seekVol.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                    override fun onProgressChanged(
                        seekBar: SeekBar?, progress: Int, fromUser: Boolean
                    ) {
                        seekBar?.setProgress(progress)
//                        ToastUtils.show("$progress")
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0)
                    }

                    override fun onStartTrackingTouch(seekBar: SeekBar?) {}

                    override fun onStopTrackingTouch(seekBar: SeekBar?) {}
                })

                seek_brightniss?.max = 255;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    seek_brightniss?.min = 1
                }
                seek_brightniss.setOnSeekBarChangeListener(object :
                    SeekBar.OnSeekBarChangeListener {
                    override fun onProgressChanged(
                        seekBar: SeekBar?, progress: Int, fromUser: Boolean
                    ) {
                        seekBar?.setProgress(progress)
                        setBrightness(progress)
                    }

                    override fun onStartTrackingTouch(seekBar: SeekBar?) {}

                    override fun onStopTrackingTouch(seekBar: SeekBar?) {}
                })

//                // 解决 ListView 拖拽滑动冲突
//                it.findViewById<ListView>(R.id.lv_test).apply {
//                    adapter = MyAdapter(
//                        this@MainActivity,
//                        arrayOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "...")
//                    )
//
//                    // 监听 ListView 的触摸事件，手指触摸时关闭拖拽，手指离开重新开启拖拽
//                    setOnTouchListener { _, event ->
//                        logger.e("listView: ${event.action}")
//                        EasyFloat.appFloatDragEnable(event?.action == MotionEvent.ACTION_UP)
//                        false
//                    }
//                }
            }.registerCallback {
                /*drag { _, motionEvent ->
                    DragUtils.registerDragClose(motionEvent, object : OnTouchRangeListener {
                        override fun touchInRange(inRange: Boolean, view: BaseSwitchView) {
//                            setVibrator(inRange)
                            view.findViewById<TextView>(com.lzf.easyfloat.R.id.tv_delete).text =
                                if (inRange) "松手删除" else "删除浮窗"

                            view.findViewById<ImageView>(com.lzf.easyfloat.R.id.iv_delete)
                                .setImageResource(
                                    if (inRange) com.lzf.easyfloat.R.drawable.icon_delete_selected
                                    else com.lzf.easyfloat.R.drawable.icon_delete_normal
                                )
                        }

                        override fun touchUpInRange() {
                            EasyFloat.dismiss()
                        }
                    }, showPattern = ShowPattern.ALL_TIME)
                }*/
            }.show()
    }


    private lateinit var countDownTimer: CountDownTimer
    private var countDownTimeRunning = false

    private var isDestory = false;

    /**
     *  订单存在时  显示倒计时
     *  sec :是分 秒
     */
    private fun remainTimeCountDown(sec: Long) {
        if (countDownTimeRunning) {
//            ToastUtils.show("结束上个倒计时")
            countDownTimeRunning = false
            countDownTimer.onFinish()
        }
        if (!countDownTimeRunning) {
            countDownTimer = object : CountDownTimer(sec * 1000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    setRemainSeconds((millisUntilFinished / 1000).toInt())
                }

                override fun onFinish() {
                    countDownTimer.cancel()
                }
            }
            countDownTimer.start()
            countDownTimeRunning = true
        }


    }

    /**
     *  定时检测应用是否处于前台  不在前台且未存在订单时 及时回到应用
     */
    private fun task2CheckFront() { // 这个服务有一定概率会被杀掉  后面如果有反馈失效，需要改为service
        lifecycleScope.launch() {
            /*while (!isDestory) {
            }*/
            endTimestamp = MmkvUtil.getLong(MmkvUtil.EndTime, 0);
            userUsing =
                endTimestamp > (System.currentTimeMillis() / 1000);// 订单是否进行中 结束时间大于当前 时间，才是没结束
            postDelayed({
                if (!userUsing) {
                    val needCheck = MmkvUtil.getBool(MmkvUtil.IsBackCheck);
                    val socketLogin = MmkvUtil.getBool(MmkvUtil.IsSocketLogin);
                    if (socketLogin) {
                        iv?.visibility = View.VISIBLE;
                    } else {
                        iv?.visibility = View.INVISIBLE;
                    }
                    val isFore = ActivityManager.getInstance().isForeground()
                    Timber.i("是否需要检测 $needCheck 是否前台 $isFore  是否使用中 $userUsing 结束时间戳 $endTimestamp ")
                    if (needCheck && !isFore) {
//                        如果在后台  等半秒再检查  省的老下单之后 又立马检测 回到应用
                        postDelayed({
                            if (!userUsing) {
                                killOther()
                                Timber.d("返回1")
                                startActivity(SplashActivity::class.java)
                            } else {
//                            如果倒计时没开始  需要初始化倒计时
                                if (orderSeconds < 1) {
                                    orderStart1()
                                }
                            }
                        }, 500)


                    }
                }
            }, 500)

        }

    }

    private fun killOther() {
        val actMng = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
        actMng.killBackgroundProcesses("com.tencent.qqlive")
    }

    private var toSpeech: TextToSpeech? = null
    private fun initTextToSpeech() {
//  https://www.xfyun.cn/doc/tts/AIkit_offline_tts/Android-SDK.html
        toSpeech = TextToSpeech(this) { status ->
            if (status == TextToSpeech.SUCCESS) {
                // 设置首选项为中文
                val result = toSpeech!!.setLanguage(Locale.CHINA)
                if (result < 0) {
                    CrashReport.postCatchedException(Throwable("语音 initTextToSpeech $result"))
                    Timber.e("语音有误 ${result}")/*if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {

                    }*/
                }


                // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
                toSpeech!!.setPitch(1.2f);
                // 设置语速
                toSpeech!!.setSpeechRate(1f)
            } else {
                Timber.e("语音初始化有误  " + status.toString())
                CrashReport.postCatchedException(Throwable("语音初始化有误 ${status.toString()}"))
            }
        }
        toSpeech!!.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
            override fun onStart(utteranceId: String?) {
                Timber.d("语音播放 onStart $utteranceId")
            }

            override fun onDone(utteranceId: String?) {
                Timber.i("语音播放 onDone $utteranceId")
            }

            override fun onError(utteranceId: String?) {
                Timber.e("语音播放 onError $utteranceId")
                ToastUtils.show("$utteranceId")
                CrashReport.postCatchedException(Throwable("语音播放onError $utteranceId"))
            }

        })
    }

    lateinit var mediaPlayer: MediaPlayer
    lateinit var mediaPlayerRe: MediaPlayer
    private lateinit var orderGuideDialog: OrderGuideDialog.Builder

    /**
     * 续费提醒
     */
    private fun renewTip() {


    }

    override fun onBackPressed() {
//        super.onBackPressed()
    }

    /**
     *  点击屏幕的提示
     */

    private fun screenTip(isNew: Boolean, msg: String) {
        Timber.i("是否在使用 $userUsing isnew:$isNew")
//        startActivity(AppListAct::class.java)//todo 仅供测试
        if (userUsing) {
//            使用中  点击屏幕无需任何 提醒  ，但是续费要提醒
            if (!isNew) {
                if (toSpeech != null) {
                    if (!toSpeech!!.isSpeaking) {
                        toSpeech!!.speak(msg, TextToSpeech.QUEUE_ADD, null, "id-${msg}")
                    } else {
                        //                 将播报过程中接收的语音缓存一下
                        //                voiceStrList.add(msg);
                    }
                }
            } else {
//                startActivity(AppListAct::class.java)
            }
        } else {
//   未使用
            if (isNew) {
                if (!mediaPlayer.isPlaying) {
                    mediaPlayer.start();
                }

                if (!orderGuideDialog.isShowing()) {
                    orderGuideDialog.show()
                    postDelayed({ orderGuideDialog.dismiss() }, 8000)
                }
            } else {
                if (toSpeech != null) {
                    if (!toSpeech!!.isSpeaking) {
                        toSpeech!!.speak(msg, TextToSpeech.QUEUE_ADD, null, "id-${msg}")
                    } else {
                        //                 将播报过程中接收的语音缓存一下
                        //                voiceStrList.add(msg);
                    }
                }

            }

        }


    }

    /**
     *   从act 接收 倒计时
     */
    fun setRemainSeconds(seconds: Int) {
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        val secs = seconds % 60
//        return String.format("%02d:%02d:%02d", hours, minutes, secs)

        val timeShow = String.format("%02d:%02d:%02d", hours, minutes, secs)

        tv_remain?.text = timeShow
        if (seconds > 0) {
            tv_remain?.visibility = View.VISIBLE
        } else {
            Timber.d("从悬浮框返回主界面")
            startActivity(MainAct::class.java)
//            tv_remain?.visibility = View.GONE
        }

    }

    private fun reqVersion() {
        val api = VersionApi()
        EasyHttp.get(this).api(api).delay(MyIntercept.getRandomDelay())
            .request(object : HttpCallback<VersionM>(this) {
                override fun onSucceed(result: VersionM) {
                    super.onSucceed(result)
                    if (result.getCode() === 1) {
                        val currentV = getVersionCode()
                        var serverV: String = result.getData().appVersion
                        if (serverV == "") {
                            serverV = "0"
                        }
                        val v = serverV.toInt()
                        Timber.d("当前版本 $currentV,$v")
                        if (currentV < v) {
                            doDownload(result.getData().downUrl)
                        }

                    } else {
                        ToastUtils.show("" + result.getMsg())
                    }
                }
            })
    }

    var isUpdateDialogShow = false

    /**
     * 进行下载 安装新版本
     */
    private fun doDownload(url: String) {
        if (isUpdateDialogShow) {
            return
        }
        val dialog = UpdateDialog.Builder(this)
        dialog.setDownloadUrl(url).setUpdateLog(getString(R.string.waiting4upgrade))
            .addOnShowListener(object : BaseDialog.OnShowListener {
                override fun onShow(dialog: BaseDialog?) {
                    true.also { isUpdateDialogShow = it }
                }
            }).addOnCancelListener(object : BaseDialog.OnCancelListener {
                override fun onCancel(dialog: BaseDialog?) {
                    true.also { isUpdateDialogShow = it }
                }

            }).addOnDismissListener(object : BaseDialog.OnDismissListener {
                override fun onDismiss(dialog: BaseDialog?) {
                    true.also { isUpdateDialogShow = it }
                }

            })

        dialog.show()
    }
}